package com.financing.platform.web.api;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.financing.platform.common.Pager;
import com.financing.platform.common.ResultCode;
import com.financing.platform.common.ResultMap;
import com.financing.platform.common.ResultMap.STATUS;
import com.financing.platform.dto.CorpProjectDTO;
import com.financing.platform.dto.FpNewProductDTO;
import com.financing.platform.dto.FpProjectTransferHisDTO;
import com.financing.platform.dto.FpRelevanceDTO;
import com.financing.platform.dto.ProjectAnnualRevenueDTO;
import com.financing.platform.dto.ProjectDTO;
import com.financing.platform.dto.ProjectExpandDTO;
import com.financing.platform.dto.ProjectRabateDTO;
import com.financing.platform.service.IFpNewProductService;
import com.financing.platform.service.IFpProjectTransferHisService;
import com.financing.platform.service.IFpRelevanceService;
import com.financing.platform.service.IProjectAnnualRevenueService;
import com.financing.platform.service.IProjectRabateService;
import com.financing.platform.service.IProjectService;
import com.financing.platform.util.DTOdateSet;
import com.financing.platform.util.StringUtil;

@Controller("fetchProductAction")
@RequestMapping("/api/fetchProduct")
@Scope("prototype")
public class FetchProductAction extends BaseAction{
	 Logger log = Logger.getLogger(FetchProductAction.class);
	
	@Autowired
	IFpNewProductService fpNewProductService;
	
	@Autowired
	IProjectService projectService;
	
	@Autowired
	IFpRelevanceService fpRelevanceService;
	
	@Autowired
	ProjectAction projectAction;
	
	@Autowired
	private IProjectAnnualRevenueService projectAnnualRevenueServiceImpl; 
	
	@Autowired
	private IProjectRabateService projectRabateSericeImpl;
	@Autowired
	private IProjectService projectServiceImpl;
	
	@Autowired
	ProjectUpdateAction projectUpdateAction;

	@Autowired
	private IFpProjectTransferHisService fpProjectTransferHisService;
	
	/**
	 * 
	
	* @Title: newProductList
	
	* @Description: 未匹配SFA新产品列表
	
	* @param @param request
	* @param @param response
	* @param @param fnProductDto
	* @param @return    设定文件
	
	* @return ResultMap    返回类型
	
	* @throws
	 */
	@RequestMapping("/newProductList.shtml")
	@ResponseBody
	public ResultMap newProductList(HttpServletRequest request, HttpServletResponse response,FpNewProductDTO fnProductDto){
		ResultMap resultMap=new ResultMap();
		try {
			if(fnProductDto.getPageNo() == null){
				fnProductDto.setPageNo(1);
			}
			if(fnProductDto.getPageSize() == null){
				fnProductDto.setPageSize(20);
			}
			//产品类型必须
			if(StringUtils.isBlank(fnProductDto.getpType())){
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.STATUS_CODE_PARAMETERS_LOSE);
				return resultMap;
			}
			//pType转化
			if("02".equals(fnProductDto.getpType())){
				fnProductDto.setpType("集合信托");
			}else{
				fnProductDto.setpType("集合资管");
			}
			
			int count = fpNewProductService.countFpNewProductList(fnProductDto);
			fnProductDto.setTotalCount(count);
			fnProductDto.setPageCount(count%fnProductDto.getPageSize() == 0 ? count/fnProductDto.getPageSize():count/fnProductDto.getPageSize()+1);
			List<Map<String,String>> list=fpNewProductService.queryFpNewProductList(fnProductDto);
			resultMap.setAttribute("list",list);
			resultMap.setAttribute("fnProductDto",fnProductDto);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		} catch (SQLException e) {
			log.error("queryFpNewProductList error",e);
			resultMap.setStatus(STATUS.ERROR);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		return resultMap;
	}
	/***
	 * 
	
	* @Title: newProductDetail
	
	* @Description: 未匹配SFA产品详情
	
	* @param @param request
	* @param @param response
	* @param @param fnProductDto
	* @param @return    设定文件
	
	* @return ResultMap    返回类型
	
	* @throws
	 */
	@RequestMapping("/newProductDetail.shtml")
	@ResponseBody
	public ResultMap newProductDetail(HttpServletRequest request, HttpServletResponse response,FpNewProductDTO fnProductDto){
		ResultMap resultMap=new ResultMap();
		try {
			if(fnProductDto.getId()==0){
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.STATUS_CODE_PARAMETERS_LOSE);
				return resultMap;
			}
			List<FpNewProductDTO> fpdto=fpNewProductService.queryFpNewProductByWhere(fnProductDto);
			if(fpdto==null||fpdto.size()==0){
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.STATUS_CODE_FETCH_PRODUCT_NOTEXIST);
				return resultMap;
			}
			resultMap.setAttribute("fpdto",fpdto.get(0));
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		} catch (SQLException e) {
			log.error("newProductDetail error",e);
			resultMap.setStatus(STATUS.ERROR);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		return resultMap;
	}
	
	/***
	 * 
	
	* @Title: deleteNewProduct
	
	* @Description:放弃抓取产品
	
	* @param @param request
	* @param @param response
	* @param @param fnProductDto
	* @param @return    设定文件
	
	* @return ResultMap    返回类型
	
	* @throws
	 */
	@RequestMapping("/deleteNewProduct.shtml")
	@ResponseBody
	public ResultMap deleteNewProduct(HttpServletRequest request, HttpServletResponse response,FpNewProductDTO fnProductDto){
		ResultMap resultMap=new ResultMap();
		try {
			if(fnProductDto.getId()==0){
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.STATUS_CODE_PARAMETERS_LOSE);
				return resultMap;
			}
			
			DTOdateSet.setUpdateInfo(fnProductDto, request.getSession());
			
			fpNewProductService.deleteFpNewProduct(fnProductDto);
			
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		} catch (Exception e) {
			log.error("deleteNewProduct error",e);
			resultMap.setStatus(STATUS.ERROR);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		return resultMap;
	}
	/***
	 * 
	
	* @Title: noBindProjectList
	
	* @Description: SFA未绑定的产品列表
	
	* @param @param request
	* @param @param response
	* @param @param fnProductDto
	* @param @return    设定文件
	
	* @return ResultMap    返回类型
	
	* @throws
	 */
	@RequestMapping("/noBindProjectList.shtml")
	@ResponseBody
	public ResultMap noBindProjectList(HttpServletRequest request, HttpServletResponse response,FpNewProductDTO fnProductDto){
		ResultMap resultMap=new ResultMap();
		try {
			//产品类型必须
			if(StringUtils.isBlank(fnProductDto.getpType())){
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.STATUS_CODE_PARAMETERS_LOSE);
				return resultMap;
			}
			
			List<Map<String, String>> noBindProjectList = fpNewProductService.noBindProjectList(fnProductDto);
			
			resultMap.setAttribute("noBindProjectList",noBindProjectList);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		} catch (Exception e) {
			log.error("noBindProjectList error",e);
			resultMap.setStatus(STATUS.ERROR);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		return resultMap;
	}
	
	/***
	 * 
	
	* @Title: bindProjectList
	
	* @Description: SFA绑定的产品列表
	
	* @param @param request
	* @param @param response
	* @param @param fnProductDto
	* @param @return    设定文件
	
	* @return ResultMap    返回类型
	
	* @throws
	 */
	@RequestMapping("/bindProjectList.shtml")
	@ResponseBody
	public ResultMap bindProjectList(HttpServletRequest request, HttpServletResponse response,FpNewProductDTO fnProductDto,Pager page){
		ResultMap resultMap=new ResultMap();
		try {
			//产品类型必须
			if(StringUtils.isBlank(fnProductDto.getpType())){
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.STATUS_CODE_PARAMETERS_LOSE);
				return resultMap;
			}
			
			int count = fpNewProductService.bindProjectListCount(fnProductDto);
			page.setTotalCount(count);
			fnProductDto.setBegin(page.getStartIndex());
			fnProductDto.setEnd(page.getPageSize());
			List<Map<String, Object>> bindProjectList =null;
			if (count > 0) {
				bindProjectList = fpNewProductService.bindProjectList(fnProductDto);
				//查找权限转移后的产品createBy
				if(bindProjectList!= null && bindProjectList.size()>=0){
					FpProjectTransferHisDTO dto = new FpProjectTransferHisDTO();
					for (Map<String, Object> map2 : bindProjectList) {
						Object o=map2.get("pId");
						dto.setPProjectId(Integer.parseInt(o+""));
						dto.setpProjectType("01");//“01：信托，资管” 
						String createBy = fpProjectTransferHisService.getTransferUserNameByProjectID(dto);
						if(!StringUtil.isNullOrEmptyStr(createBy)){
							map2.put("createBy", createBy);
						}
					}
				}
			}
			resultMap.setAttribute("bindProjectList",bindProjectList);
			resultMap.setAttribute("page",page);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		} catch (Exception e) {
			log.error("bindProjectList error",e);
			resultMap.setStatus(STATUS.ERROR);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		return resultMap;
	}
	
	/***
	 * 
	
	* @Title: unbindProduct
	
	* @Description:解除绑定 SFA产品和壹财富
	
	* @param @param request
	* @param @param response
	* @param @param fnProductDto
	* @param @return    设定文件
	
	* @return ResultMap    返回类型
	
	* @throws
	 */
	@RequestMapping("/unbindProduct.shtml")
	@ResponseBody
	public ResultMap unbindProduct(HttpServletRequest request, HttpServletResponse response,FpRelevanceDTO fpRelevanceDTO){
		ResultMap resultMap=new ResultMap();
		try {
			//绑定id必须要
			if(fpRelevanceDTO.getId()==0){
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.STATUS_CODE_PARAMETERS_LOSE);
				return resultMap;
			}
			DTOdateSet.setUpdateInfo(fpRelevanceDTO, request.getSession());
			fpRelevanceService.deleteFpRelevance(fpRelevanceDTO);
			
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		} catch (Exception e) {
			log.error("unbindProduct error",e);
			resultMap.setStatus(STATUS.ERROR);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		return resultMap;
	}
	
	/***
	 * 
	
	* @Title: addFpRelevance
	
	* @Description: 新增抓取产品和SFA产品绑定关系
	
	* @param @param request
	* @param @param response
	* @param @param fRelevanceDto
	* @param @return    设定文件
	
	* @return ResultMap    返回类型
	
	* @throws
	 */
	@RequestMapping("/addFpRelevance.shtml")
	@ResponseBody
	public ResultMap addFpRelevance(HttpServletRequest request, HttpServletResponse response,FpRelevanceDTO fRelevanceDto){
		ResultMap resultMap=new ResultMap();
		try {
			//绑定关系
			if(fRelevanceDto.getpId()==0||fRelevanceDto.getFetchPId()==0||StringUtils.isBlank(fRelevanceDto.getAssociationType())){
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.STATUS_CODE_PARAMETERS_LOSE);
				return resultMap;
			}
			//判断是否存在相同类型关系   产品类型为相同时， 进行判断
			if("1".equals(fRelevanceDto.getAssociationType())){
				FpRelevanceDTO fpDto=new FpRelevanceDTO();
				fpDto.setFetchPId(fRelevanceDto.getFetchPId());
				fpDto.setAssociationType(fRelevanceDto.getAssociationType());
				List<Map<String, String>> queryFpRelevance = fpRelevanceService.queryFpRelevance(fpDto);
				if(queryFpRelevance.size()>0){//已与其他产品绑定该关系
					resultMap.setStatus(STATUS.FAILE);
					resultMap.setStatusCode(ResultCode.STATUS_CODE_REPEAT_BIND);
					return resultMap;
				}
			}
			
			//查看产品是否存在
			ProjectDTO projectDto=new ProjectDTO();
			projectDto.setId(fRelevanceDto.getpId());
			List<ProjectDTO> projectResult = projectService.queryAllProject(projectDto);
			if(projectResult.size()==0){
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.STATUS_CODE_PRODUCT_NOTEXIST);
				return resultMap;
			}
			//查看url是否存在  
			FpNewProductDTO fnProductDto=new FpNewProductDTO();
			fnProductDto.setId(fRelevanceDto.getFetchPId());
			List<FpNewProductDTO> fnProductList = fpNewProductService.queryFpNewProductByWhere(fnProductDto);
			if(fnProductList.size()==0){//抓取产品的url不存在
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.STATUS_CODE_FETCH_PRODUCT_NOTEXIST);
				return resultMap;
			}//建立关系
			fRelevanceDto.setpType(projectResult.get(0).getpType());
			DTOdateSet.setCreateInfo(fRelevanceDto, request.getSession());
			DTOdateSet.setUpdateInfo(fRelevanceDto, request.getSession());
			fpRelevanceService.addFpRelevance(fRelevanceDto);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		} catch (Exception e) {
			log.error("addFpRelevance error",e);
			resultMap.setStatus(STATUS.ERROR);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		return resultMap;
	}
	
	
	/***
	 * 
	
	* @Title: addProjectByFetch
	
	* @Description: 新增抓取产品的SFA产品
	
	* @param @param request
	* @param @param response
	* @param @param fRelevanceDto
	* @param @return    设定文件
	
	* @return ResultMap    返回类型
	
	* @throws
	 */
	@RequestMapping("/addProjectByFetch.shtml")
	@ResponseBody
	public ResultMap addProjectByFetch(HttpServletRequest request, HttpServletResponse response,ProjectDTO projectDTO,ProjectExpandDTO projectExpandDTO,CorpProjectDTO corpProjectDTO,String copyType){
		ResultMap resultMap=new ResultMap();
		try {
			String fetchId=request.getParameter("fetchId");
			if(StringUtils.isBlank(fetchId)){
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.STATUS_CODE_PARAMETERS_LOSE);
				return resultMap;
			}
			
			//查看url是否存在  
			FpNewProductDTO fnProductDto=new FpNewProductDTO();
			fnProductDto.setId(Integer.parseInt(fetchId));
			List<FpNewProductDTO> fnProductList = fpNewProductService.queryFpNewProductByWhere(fnProductDto);
			if(fnProductList.size()==0){//抓取产品的url不存在
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.STATUS_CODE_FETCH_PRODUCT_NOTEXIST);
				return resultMap;
			}
			
			//新增产品
			ResultMap addProject = projectAction.addProject(request, response, projectDTO, projectExpandDTO, corpProjectDTO, copyType);
			if("0000".equals(addProject.getStatusCode())){
				
				ProjectDTO proj = (ProjectDTO) addProject.getAttribute("projectDTO");
				//绑定产品和 壹财富产品关系
				FpRelevanceDTO fRelevanceDto=new FpRelevanceDTO();
				fRelevanceDto.setpId(proj.getId());
				fRelevanceDto.setFetchPId(Integer.parseInt(fetchId));
				fRelevanceDto.setpType(proj.getpType());
				fRelevanceDto.setAssociationType("1");//相同
				DTOdateSet.setCreateInfo(fRelevanceDto, request.getSession());
				DTOdateSet.setUpdateInfo(fRelevanceDto, request.getSession());
				fpRelevanceService.addFpRelevance(fRelevanceDto);
				
				resultMap.setAttribute("projectDTO",proj);
				resultMap.setStatus(STATUS.SUCCESS);
				resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
			}else{
				resultMap.setStatus(addProject.getStatus());
				resultMap.setStatusCode(addProject.getStatusCode());
			}
		} catch (Exception e) {
			log.error("addProjectByFetch error",e);
			resultMap.setStatus(STATUS.ERROR);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		return resultMap;
	}
	
	/***
	 * 
	
	* @Title: updateProjectByFetch
	
	* @Description: 同步产品信息
	
	* @param @param request
	* @param @param response
	* @param @param fRelevanceDto
	* @param @return    设定文件
	
	* @return ResultMap    返回类型
	
	* @throws
	 */
	@RequestMapping("/updateProjectByFetch.shtml")
	@ResponseBody
	public ResultMap updateProjectByFetch(HttpServletRequest request, HttpServletResponse response,ProjectDTO projectDto){
		ResultMap resultMap=new ResultMap();
		try {
			//募集说明
			String pRecruitmentSummary=request.getParameter("pRecruitmentSummary");
			//抓取产品的id
			String fetchId=request.getParameter("fetchId");
			
			if(StringUtils.isBlank(fetchId)||StringUtils.isBlank(pRecruitmentSummary)){
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.STATUS_CODE_PARAMETERS_LOSE);
				return resultMap;
			}
			
			//新增产品
			ResultMap addProject = projectUpdateAction.updateProjectAnnualRevenue(request, response,projectDto);
			if("0000".equals(addProject.getStatusCode())){
				ProjectDTO proj=new ProjectDTO();
				proj.setId(projectDto.getId());
				proj.setpRecruitmentSummary(pRecruitmentSummary);
				DTOdateSet.setUpdateInfo(proj, request.getSession());
				//更新募集说明   
				fpNewProductService.updatepRecruitmentSummaryById(proj);
				
				FpNewProductDTO fnProductDto=new FpNewProductDTO();
				fnProductDto.setId(Integer.parseInt(fetchId));
				DTOdateSet.setUpdateInfo(fnProductDto, request.getSession());
				//更新抓取产品状态 为  false
				fpNewProductService.updateStatus(fnProductDto);
				resultMap.setStatus(STATUS.SUCCESS);
				resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
			}else{
				resultMap.setStatus(addProject.getStatus());
				resultMap.setStatusCode(addProject.getStatusCode());
			}
		} catch (Exception e) {
			log.error("addProjectByFetch error",e);
			resultMap.setStatus(STATUS.ERROR);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		return resultMap;
	}
	
	
	/***
	 * 
	
	* @Title: projectDetail
	
	* @Description:产品详情
	
	* @param @param request
	* @param @param response
	* @param @param fRelevanceDto
	* @param @return    设定文件
	
	* @return ResultMap    返回类型
	
	* @throws
	 */
	@RequestMapping("/projectDetail.shtml")
	@ResponseBody
	public ResultMap projectDetail(HttpServletRequest request, HttpServletResponse response,ProjectDTO projectDto){
		ResultMap resultMap=new ResultMap();
		try {
			if(projectDto.getId()==null||projectDto.getId()==0){
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.STATUS_CODE_PARAMETERS_LOSE);
				return resultMap;
			}
			//查询产品
			List<ProjectDTO>  projectList = projectServiceImpl.queryAllProject(projectDto);
			if(projectList.size()==0){
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.STATUS_CODE_PRODUCT_NOTEXIST);
				return resultMap;
			}
			
			//查询年化益率信息
			List<ProjectAnnualRevenueDTO> projectAnnualRevenueList = projectAnnualRevenueServiceImpl.queryProjectAnnualRevenue(projectList.get(0).getId());
			//查询返佣比例
			ProjectRabateDTO projectRabateDTO = new ProjectRabateDTO();
			projectRabateDTO.setpId(projectList.get(0).getId());
			List<ProjectRabateDTO>  projectRabateList = projectRabateSericeImpl.queryProjectRabate(projectRabateDTO);
			for(ProjectRabateDTO projectRabate : projectRabateList){
				projectRabate.setpCorePrice(null);
			}
			resultMap.setAttribute("projectRabateList", projectRabateList);
			//封装产品信息
			Map<String,Object> pro=new HashMap<String, Object>();
			pro.put("pName", projectList.get(0).getpName());
			pro.put("pRecruitmentSummary", projectList.get(0).getpRecruitmentSummary());
			pro.put("id", projectList.get(0).getId());
			pro.put("pSaleStatus", projectList.get(0).getpSaleStatus());
			pro.put("pSaleTimeStart", projectList.get(0).getpSaleTimeStart());
			resultMap.setAttribute("project",pro);
			resultMap.setAttribute("projectAnnualRevenueList", projectAnnualRevenueList);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		} catch (Exception e) {
			log.error("projectDetail error",e);
			resultMap.setStatus(STATUS.ERROR);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		return resultMap;
	}
	
	
	
	
}
